package netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class UdpClient {
    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "7686"));

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new LoggingHandler(LogLevel.INFO));
                            p.addLast(new UdpClientHandler());
                        }
                    });

            // bind 0
            ChannelFuture f = b.bind(0).sync();

            log.info("connect to {}:{}", HOST, PORT);

            Channel ch = f.channel();

            for (int i = 0; i < 10; i++) {
                ch.eventLoop().schedule(() -> {
                    ch.writeAndFlush(new DatagramPacket(
                            Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                            SocketUtils.socketAddress("255.255.255.255", PORT))
                    );
                }, i + 1, TimeUnit.SECONDS);
            }

            // Wait until the connection is closed.
            ch.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
